package com.example.demo.service;

import com.example.demo.entity.Order;
import com.example.demo.entity.User;
import com.example.demo.entity.vo.OrderVO;
import com.example.demo.mapper.DishMapper;
import com.example.demo.mapper.DishOrderMapper;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DishOrderMapper dishOrderMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private UserMapper userMapper;

    public List<OrderVO> getList(Integer userId, Integer orderId, Integer pSize, Integer pIndex) {
        List<OrderVO> list = orderMapper.getList(userId, orderId, pSize, pIndex);
        if (orderId != null) {
            // 根据 orderId 搜索, 至多只有一个订单
            User user = userMapper.getById(list.get(0).getUserId());
            list.get(0).setUsername(user.getUsername());
            list.get(0).setPhone(user.getPhone());
        }
        return list;
    }

    public int update(Integer orderId, Integer userId, Integer state) {
        return orderMapper.updateState(orderId, userId, state);
    }

    public int add(Order order, List<Integer> arrDishId) {
        // 用户下单， 先判断选择的菜品是否都是有效的 （上架的）
        if (dishMapper.checkDishId(arrDishId) == arrDishId.size()) {
            // 添加订单
            if (orderMapper.add(order) > 0) {
                // 添加订单-菜品
                return dishOrderMapper.add(order.getId(), arrDishId);
            }
        }
        return 0;
    }

    public int getCount(Integer userId) {
        return orderMapper.getCount(userId);
    }
}
